package com.zc.basic.infra.mybatis.injector;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.stream.Collectors;

public class SaveEntity extends AbstractMethod {

    private static final String SAVE_ENTITY = "saveEntity";

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {

        boolean flag = false;
        for (Method method : mapperClass.getMethods()) {
            if (SAVE_ENTITY.equals(method.getName())) {
                flag = true;
                break;
            }
        }

        if (flag) {
            KeyGenerator keyGenerator = NoKeyGenerator.INSTANCE;
            SqlMethod sqlMethod = SqlMethod.INSERT_ONE;
            String columnScript = SqlScriptUtils.convertTrim(tableInfo.getAllInsertSqlColumnMaybeIf(null), "(", ")", (String) null, ",");


            // TODO 改写#{}

            String valuesScript = SqlScriptUtils.convertTrim(tableInfo.getAllInsertSqlPropertyMaybeIf(null), "(", ")", (String) null, ",");
            String keyProperty = null;
            String keyColumn = null;
            if (StringUtils.isNotBlank(tableInfo.getKeyProperty())) {
                if (tableInfo.getIdType() == IdType.AUTO) {
                    keyGenerator = Jdbc3KeyGenerator.INSTANCE;
                    keyProperty = tableInfo.getKeyProperty();
                    keyColumn = tableInfo.getKeyColumn();
                } else if (null != tableInfo.getKeySequence()) {
                    keyGenerator = TableInfoHelper.genKeyGenerator(this.getMethod(sqlMethod), tableInfo, this.builderAssistant);
                    keyProperty = tableInfo.getKeyProperty();
                    keyColumn = tableInfo.getKeyColumn();
                }
            }

            String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), columnScript, valuesScript);
            SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
            return this.addInsertMappedStatement(mapperClass, modelClass, SAVE_ENTITY, sqlSource, keyGenerator, keyProperty, keyColumn);
        }
        return null;

    }

}
